package top.lingchen.webfluxdemo2;

import org.springframework.http.ReactiveHttpInputMessage;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.http.server.HttpServer;
import top.lingchen.webfluxdemo2.handler.UserHandler;
import top.lingchen.webfluxdemo2.service.UserService;
import top.lingchen.webfluxdemo2.service.impl.UserServiceImpl;

import java.io.IOException;

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;

/**
 * @Author 凌宸
 * @create 2021-12-01 下午 7:38
 * @Description
 * @Version 1.0
 */
public class Server {

    // 创建Router路由
    public RouterFunction<ServerResponse> routingFunction(){
        UserService userService = new UserServiceImpl();
        UserHandler userHandler = new UserHandler(userService);

        return RouterFunctions.route(
                GET("/users/{id}").and(accept(APPLICATION_JSON)),userHandler::getUserById)
                .andRoute(GET("/users").and(accept(APPLICATION_JSON)),userHandler::getAllUsers);
    }

    // 创建服务器完成适配
    public void createReactorServer(){
        // 路由和 handler 适配
        RouterFunction<ServerResponse> route = routingFunction();
        HttpHandler handler = toHttpHandler(route);
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
        // 创建服务器
        HttpServer httpServer = HttpServer.create();
        httpServer.handle(adapter).bindNow();
    }

    // 最终调用
    public static void main(String[] args) throws IOException {
        Server server = new Server();
        server.createReactorServer();
        System.out.println("enter to exit");
        System.in.read();
    }
}
